<?php

namespace App\Http\Middleware;

use App\Models\VueAdmin as Admin;
use App\Exceptions\ParameterException;

use Closure;

class Permission
{
    const CODE_AUTHFAIL = 401;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('token');
        if (!$token) {
            $token = $request->input('token'); // 调试用
        }
        if (!$token) {
            throw new ParameterException([
                'code' => self::CODE_AUTHFAIL,
                'msg' => 'token 不能为空！'
            ]);
        }

        $origin = $request->header('origin');
        if (strstr($origin, 'http://127.0.0.1') !== false || strstr($origin, 'http://localhost') !== false || $request->input('token')) {
            // TODO 用 token ，只能登录一次
            //$admin = Admin::where('id', $token)->first();
            $admin = Admin::where('token', $token)->first();
            if (!$admin) {
                throw new ParameterException([
                    'code' => self::CODE_AUTHFAIL,
                    'msg' => 'token值不正确，请重新登录！'
                ]);
            }
            // 超过一天退出登录
            if ($admin['token_expire'] < time()) {
                throw new ParameterException([
                    'code' => self::CODE_AUTHFAIL,
                    'msg' => 'token值已过期，请重新登录！'
                ]);
            }
        } else {
            // 记住密码
            $cookie_admin = cookie('admin');
            if ($cookie_admin) {
                if (!session('admin')) {
                    session('admin', json_decode($cookie_admin, true));
                }
            }
            $admin = session('admin');
            if (!$admin || $admin['token'] !== $token) {
                throw new ParameterException([
                    'code' => self::CODE_AUTHFAIL,
                    'msg' => 'token值不正确，请重新登录！',
                ]);
            }
            if ($admin['token_expire'] < time()) {
                throw new ParameterException([
                    'code' => self::CODE_AUTHFAIL,
                    'msg' => 'token值已过期，请重新登录！'
                ]);
            }
        }

        return $next($request);
    }
}
